package com.docking.heylo.web.interceptor;

import com.docking.heylo.ThreadContext;
import com.docking.heylo.exception.GeneralException;
import com.docking.heylo.pojo.Audience;
import com.docking.heylo.pojo.Request;
import com.docking.heylo.service.IUserService;
import com.docking.heylo.utils.JwtHelper;
import com.docking.heylo.utils.ResponseUtil;
import com.docking.heylo.web.utils.ResultUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/***
 * 授权校验
 */
@Component
public class AuthorityInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService userService;

    @Autowired
    private Audience audience;

    /***
     * 校验token是否有效
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try{
            String          token       = request.getHeader("authority-token");
            if(StringUtils.isEmpty(token)){
                throw new GeneralException("请求无效");
            }

            Request userRequest = userService.userForToken(token);

            userRequest.setIp(getIp(request));
            ThreadContext.authorize.set(userRequest);
            return true;
        }catch (GeneralException e){
            ResponseUtil.write(ResultUtil.error(-1, e.getMessage()), response);
            return false;
        }
    }

    public Integer userForToken(String token) {
        Claims claims = JwtHelper.parseJWT(token, audience.getBase64Secret());
        if(claims == null){
            throw new GeneralException("请求无效");
        }
        return Integer.parseInt(claims.get("userId").toString());
    }


    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");

        //多次反向代理后会有多个ip值，第一个ip才是真实ip
        if(isIp(ip)){
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }

        ip = request.getHeader("X-Real-IP");
        if(isIp(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }

    public static boolean isIp(String ip){
        return !StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip);
    }

}
